//
//  LLGComposePictureView.swift
//  Weibo30LLG
//
//  Created by 李龙 on 16/8/17.
//  Copyright © 2016年 lilong. All rights reserved.
//

import UIKit

//重用标记
let LLGComposePictureViewCellIdentifier = "LLGComposePictureViewCellIdentifier"

class LLGComposePictureView: UICollectionView {
    
    //添加图片闭包
    var didSelectedAddImageClosure: (() -> ())?

    //图片数据源
    lazy var images: [UIImage] = [UIImage]()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let flowLayout = UICollectionViewFlowLayout()
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: --添加控件,设置约束
    private func setupUI() {
    
        backgroundColor = RandomColor()
        //默认隐藏
        hidden = true
        
        //注册cell
        registerClass(LLGComposePictureViewCell.self, forCellWithReuseIdentifier: LLGComposePictureViewCellIdentifier)
        //设置数据源代理
        dataSource = self
        //代理
        delegate = self
    }
    
    // MARK: --添加图片方法
    func addImage(image: UIImage) {
        
        //添加图片最多9张
        if images.count >= 9 {
        
            return
        }
        
        //显示
        hidden = false
    
        images.append(image)
        
        reloadData()
    }
    
    // MARK: --计算cell大小
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //间距
        let itemMargin: CGFloat = 5
        //宽度
        let itemWidth = (width - 2 * itemMargin) / 3
        //获取flowLayout
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        //大小
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        //水平间距
        flowLayout.minimumInteritemSpacing = itemMargin
        //垂直间距
        flowLayout.minimumLineSpacing = itemMargin
    }
}

//数据源方法
extension LLGComposePictureView: UICollectionViewDataSource, UICollectionViewDelegate {

    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        //如果是0或者9,则显示正常图片
        if images.count == 0 || images.count == 9 {
        
            return images.count
        } else {
            //否则多显示一张加号
            return images.count + 1
        }
        
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LLGComposePictureViewCellIdentifier, forIndexPath: indexPath) as! LLGComposePictureViewCell
        
        //判断索引等于最后一个cell
        if indexPath.item == images.count {
        
            //设置为空
            cell.image = nil
        } else {
            //绑定图片
            cell.image = images[indexPath.item]
        }

        //cell删除闭包回调
        cell.deleteButtonClosure = { [weak self] in
        
            self?.images.removeAtIndex(indexPath.item)
            
            //如果没有数据,则隐藏视图
            if self?.images.count == 0 {
            
                self?.hidden = true
            }
            
            self?.reloadData()
        }
        
        return cell
    }
    
    // MARK: --选中cell
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        if indexPath.item == images.count {
            
            //取消选中
            collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        
            didSelectedAddImageClosure?()
        }
        
    }
}


//自定义cell
class LLGComposePictureViewCell: UICollectionViewCell {
    
    //删除按钮闭包
    var deleteButtonClosure: (() -> ())?
    
    //图片
    var image: UIImage? {
    
        didSet {
            //判断设置图片
            if image == nil {
                imageView.image = UIImage(named: "compose_pic_add")
                
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                
                deleteButton.hidden = true
            } else {
                imageView.image = image
                imageView.highlightedImage = nil
                deleteButton.hidden = false
            }
 
        }
    }
    
    //显示图片
    private lazy var imageView: UIImageView = UIImageView()
    
    //删除图片按钮
    private lazy var deleteButton: UIButton = {
    
        let button = UIButton()
        //添加点击事件
        button.addTarget(self, action: "deleteAction", forControlEvents: .TouchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        return button
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: --添加控件,设置约束
    private func setupUI() {
        
        //添加控件
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        
        //设置约束
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView)
            make.trailing.equalTo(contentView)
        }
    }
    
    // MARK: --删除按钮点击事件
    @objc private func deleteAction() {
    
        deleteButtonClosure?()
        
    }
}
